<template>
  <el-dialog v-model="show" title="视频本地上传" append-to-body width="1000px" :close-on-click-modal="false" @close="resetForm">
    <div class="video-upload-box" v-loading="submitLoading">
      <div class="inner-video-upload">
        <div class="video-upload-content">
          <el-form ref="videoFormRef" :rules="rules" :model="videoForm" label-width="100px" label-position="left" size="large">
            <el-form-item label="上传视频" prop="url">
              <div class="upload-option" v-if="imgUploadList.length === 0">
                <el-upload ref="uploadRef" v-model:file-list="imgUploadList" class="upload-demo" action :before-upload="handleBeforeUpload" :http-request="handleUpload" :show-file-list="false" accept=".mp4" :limit="1">
                  <template #trigger>
                    <el-button type="primary">点击上传</el-button>
                  </template>
                  <p>视频大小不得超过{{ maxSize + 'MB' }}</p>
                </el-upload>
              </div>
              <div class="upload-process" v-else>
                <div v-for="item in imgUploadList" :key="item.uid">
                  <div class="video-title">
                    <p>{{ item.title }}</p>
                    <el-icon @click="handleResetVideo">
                      <CloseBold />
                    </el-icon>
                  </div>
                  <div class="progress-box" v-show="item.percentage !== 100">
                    <el-progress :percentage="item.percentage" :status="item.status === 'success' ? 'success' : ''" :stroke-width="20" :text-inside="true" />
                  </div>
                  <el-button size="small" text type="primary" v-show="item.percentage !== 100">取消上传</el-button>
                  <p class="success-span" v-show="item.percentage === 100">上传成功!</p>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input v-model="videoForm.title" placeholder="上传完成后将自动填写标题，可修改"></el-input>
            </el-form-item>
            <el-form-item label="视频封面" prop="thumb">
              <div>
                <div class="video-covers" v-if="videoForm.thumb === ''">
                  <div class="video-covers-item" :class="{ active: currentCover === index }" v-for="(item, index) in covers" :key="index" @click="handleChangeChoose(index)">
                    <div class="check-box">
                      <el-icon>
                        <Check />
                      </el-icon>
                    </div>
                    <img :src="item" alt />
                  </div>
                  <div class="video-covers-item no-form-img" @click="showCoverChoose = true">
                    <i class="iconfont">&#xe668;</i>
                    <p>添加封面图</p>
                  </div>
                </div>
                <div class="video-covers" v-else>
                  <div class="video-covers-item">
                    <img :src="videoForm.thumb" alt />
                  </div>
                </div>
                <div class="cover-option-btn-box">
                  <el-button type="primary" text @click="handleChooseCover" v-if="videoForm.thumb === ''" :disabled="covers.length === 0">确认选择</el-button>
                  <el-button type="primary" text @click="handleResetCover" v-else>重新选择</el-button>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="视频描述" prop="description">
              <el-input v-model="videoForm.description" type="textarea" rows="6" resize="none"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- <ImageUpload v-model:showDialog="showCoverChoose" :limit="1" @getImage="insertImage" :isToJpg="true"></ImageUpload> -->
      <FilesUpload v-if="showCoverChoose" v-model:showDialog="showCoverChoose" modelId="1" :limit="1" :isPublic="true" @getFileList="insertImage" :isToJpg="true"></FilesUpload>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirmUpload(videoFormRef)">确认</el-button>
        <el-button @click="show = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, reactive, ref } from 'vue'
import { splitUpload } from '@/utils/upload'
import { useStore } from 'vuex'
import { CloseBold, Check } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { FilesUpload } from '@ruifox-cms/components'

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  videoForm: {
    type: Object,
    default: () => {},
  },
})
const showCoverChoose = ref(false)
console.log('props.videoForm', props.videoForm)
const emits = defineEmits(['update:show', 'uploadCallback'])
const store = useStore()
const show = computed({
  get() {
    return props.show
  },
  set(val) {
    emits('update:show', val)
  },
})
const defaultVideoForm = {
  id: null,
  url: '',
  title: '',
  description: '',
  thumb: '',
}
const covers = ref([])
const moreCovers = ref([])
const videoForm = reactive(Object.assign({}, defaultVideoForm))
if (props.videoForm) {
  Object.assign(videoForm, props.videoForm)
}
// 校验规则
const rules = reactive({
  url: [{ required: true, message: '请上传视频' }],
  title: [{ required: true, message: '请填写视频标题' }],
  thumb: [{ required: true, message: '请选择视频封面' }],
})
const imgUploadList = ref([])
// 获取视频上传地址
const splitActionUrl = ref(store.state.content.splitActionUrl)
const maxSize = computed(() => {
  let currentSite = store.state.site.currentSite
  return currentSite.setting.maxSize ? currentSite.setting.maxSize : 2000
})
const allowExt = computed(() => {
  let currentSite = store.state.site.currentSite
  return currentSite.setting.ext ? currentSite.setting.ext : 'mp4|avi|rmvb|mov|wmv|flv|mkv'
})

const handleBeforeUpload = async (file) => {
  if (file.size / (1024 * 1024) > maxSize.value) {
    ElMessage.error('上传视频不能超过' + maxSize.value + 'MB')
    return false
  } else if (!allowExt.value.split('|').includes(file.type.split('/')[1])) {
    ElMessage.error('视频上传不支持' + file.type.split('/')[1] + '格式')
    return false
  }
  return true
}
// 视频上传使用分片上传
const handleUpload = async (option) => {
  try {
    let res = await splitUpload(option.file, splitActionUrl.value, option.onProgress, 5 * 1024 * 1024)
    handleUploadSuccess(res, option.file)
  } catch (e) {
    console.log(e)
  }
}

// 添加封面图
const insertImage = (imgList) => {
  covers.value = covers.value.concat(
    imgList.map((item) => {
      return item.url
    })
  )
  currentCover.value = covers.value.length - 1
  videoForm.thumb = covers.value[currentCover.value]
}
const currentCover = ref(0)
const handleChooseCover = () => {
  videoForm.thumb = covers.value[currentCover.value]
}
const handleChangeChoose = (index) => {
  currentCover.value = index
}
const handleResetCover = () => {
  videoForm.thumb = ''
}
// 提交表单
const videoFormRef = ref()
const submitLoading = ref(false)

const handleConfirmUpload = async (formEl) => {
  // 提交表单
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      let _item = {
        url: videoForm.url,
        uid: videoForm.id,
        title: videoForm.title,
        thumb: videoForm.thumb,
        percentage: 100,
      }
      emits('uploadCallback', _item)
      emits('update:show', false)
    }
  })
}
const uploadLoading = ref(false)
const handleUploadSuccess = async (res, file) => {
  const _file = imgUploadList.value.find((item) => item.uid === file.uid)

  if (_file) {
    if (process.env.NODE_ENV === 'development') {
      if (res.url.includes('192.168.2.150')) {
        res.url = res.url.replace('192.168.2.150', '10.10.0.19')
      }
    }
    _file.url = res.url
  }
  // covers.value = res.data.video_list.thumb ? res.data.video_list.thumb : []
  // 赋值表单
  videoForm.url = res.url
  videoForm.title = res.oriName
  uploadLoading.value = false
}
// 重新上传
const handleResetVideo = () => {
  covers.value = []
  moreCovers.value = []
  Object.assign(videoForm, defaultVideoForm)
  currentCover.value = 0
  imgUploadList.value = []
}

// 重置表单
const resetForm = () => {
  covers.value = []
  moreCovers.value = []
  Object.assign(videoForm, defaultVideoForm)
  currentCover.value = 0
  imgUploadList.value = []
  videoFormRef.value.resetFields()
}
</script>

<style scoped lang="scss">
.video-upload-box {
  .video-upload-content {
    margin: 20px auto;
    background-color: $white;
    border-radius: 4px;
    box-sizing: border-box;
    padding: 0 45px 40px;
    .upload-option p {
      font-size: 12px;
    }
    .checkbox-item {
      display: flex;
      align-items: center;
      .el-checkbox {
        width: 160px;
      }
      span {
        font-size: 12px;
        color: #aaaaaa;
      }
    }
    .video-covers {
      display: flex;
      flex-wrap: wrap;
      .video-covers-item {
        width: 160px;
        height: 90px;
        border: 1px solid $weightBar;
        background-color: #f2f2f2;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        margin: 0 10px 10px 0;
        box-sizing: border-box;
        transition: all 0.2s;
        position: relative;
        &.active {
          border-color: $mainColor;
          box-shadow: 0 0 10px rgba(#000, 0.2);
          background-color: $focusContent;
          .check-box {
            display: flex;
            background-color: $mainColor;
          }
        }
        img {
          max-width: 100%;
          max-height: 100%;
        }
        .check-box {
          display: none;
          align-items: center;
          justify-content: center;
          height: 20px;
          width: 20px;
          position: absolute;
          left: 5px;
          top: 5px;
          background-color: #fff;
          i {
            color: #fff;
          }
        }
        &:hover {
          .check-box {
            display: flex;
          }
        }
      }
      .no-form-img {
        width: 160px;
        height: 90px;
        color: $hoverColor;
        i {
          font-size: 40px;
          margin-bottom: 5px;
        }
        p {
          margin-top: 5px;
          line-height: 16px;
        }
      }
    }
    .upload-process {
      width: 100%;
      .video-title {
        p {
          @include textEllipsis(21px, 1);
        }
        display: flex;
        align-items: center;
        i {
          margin-left: 10px;
          cursor: pointer;
        }
      }
      p.success-span {
        color: #2cbf77;
        font-size: 14px;
      }
    }
  }
}
</style>
